package com.share.shop.h5.web.user;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.share.common.common.LoginInfo;
import com.share.common.common.Result;
import com.share.common.utils.UUIDUtil;
import com.share.config.redis.RedisTokenManager;
import com.share.shop.h5.model.db.User;
import com.share.shop.h5.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author author
 * @since 2023-03-07
 */

@Slf4j
@RestController
@Api("用户模块")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RedisTokenManager tokenManager;
    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private IUserService userService;

    @ApiOperation("微信code登录")
    @ApiParam(name = "code", value = "微信的js获取的code")
    @GetMapping(value = "/wx/login")
    public Result payAsyncNotify(String code) {
        try {
            //1获取openid
            WxMaJscode2SessionResult res = wxMaService.jsCode2SessionInfo(code);
            String openid = res.getOpenid();
            String sessionKey = res.getSessionKey();
            String unionid = res.getUnionid();


            //2.获取用户信息
            User user = userService.createOrUpdateUser(openid, sessionKey, unionid);
            LoginInfo loginInfo = new LoginInfo();
            String token = genToken(user);//生成token
            loginInfo.setToken(token);
            loginInfo.setUserId(user.getId());

            /*那用户信息存入redis*/
            String loginStr = JSON.toJSONString(user);
            log.info("用户信息存入redis,token={},loginUser={}", token, loginStr);
            boolean saveFlag = tokenManager.setUserInfo(token, loginStr);
            if (!saveFlag) {
                return Result.failure("存储到redis系统异常");
            }

            JSONObject reJson = JSON.parseObject(JSON.toJSONString(loginInfo));

            log.info("返回给页面的登录信息={}", JSON.toJSON(reJson));
            return Result.success(reJson);
        } catch (Exception e) {
            return Result.failure("授权失败");
        }
    }


    //生成token
    private String genToken(User user) {
        String token = null;
        if ("test".equals(user.getOpenid())) {
            token = "test";
        } else {
            token = UUIDUtil.genUUId();
        }
        return token;
    }
}